package com.sam.security.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.opensymphony.xwork2.ActionSupport;
import com.sam.security.service.SecurityService;

/**
 * @project EMan
 * @author Sam
 * @version
 * @date Feb 27, 2009 4:05:35 PM
 */
public class ServletContextLoaderListener extends ActionSupport implements ServletContextListener {

	//
	private static final long serialVersionUID = 1L;
	private SecurityService securityService;
	protected Logger log = LoggerFactory.getLogger(getClass());

	/*
	 * (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		servletContextEvent.getServletContext().removeAttribute("urlAuthorities");
	}

	public void contextInitialized(ServletContextEvent servletContextEvent) {
		log.info("Secutity Initializing...");
		ServletContext servletContext = servletContextEvent.getServletContext();
		List<Map<String, Object>> res = getSecurityManager(servletContext).queryRequestMap();
		Map<String, String> urlAuthorities = new HashMap<String, String>();
		for (Map<String, Object> map : res) {
			urlAuthorities.put((String) map.get("resourceString"), (String) map
					.get("userFunctionName"));
		}
		servletContext.setAttribute("urlAuthorities", urlAuthorities);
	}

	/**
	 * Get SecurityManager from ApplicationContext
	 * @param servletContext
	 * @return
	 */
	protected SecurityService getSecurityManager(ServletContext servletContext) {
		return (SecurityService) WebApplicationContextUtils
				.getWebApplicationContext(servletContext).getBean("securityService");
	}

	public SecurityService getSecurityService() {
		return securityService;
	}

	public void setSecurityService(SecurityService securityService) {
		this.securityService = securityService;
	}

}
